/**
 * <pre>
 * Title: 		LinksController.java
 * Project: 	itfinoss
 * Author:		pengfangliang
 * Create:	 	2012-12-14 下午05:47:27
 * Copyright: 	Copyright (c) 2012
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.itfinoss.controller.links;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.fckeditor.handlers.PropertiesLoader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.model.Order.OrderType;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.persist.Links;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.controller.article.ArticleController;
import com.hengpeng.itfinoss.service.ServiceFactory;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * <pre>
 *  友情链接控制器
 * </pre>
 * @author pengfangliang
 * @version 1.0, 2012-12-14
 */
@SuppressWarnings("restriction")
@Controller
@RequestMapping("/links")
public class LinksController extends BaseController
{
	private final static Log logger = LogFactory.getLog(ArticleController.class);

	@Autowired
	private ServiceFactory serviceFactory;

	private final static String FILESEPARATOR = "/";// File.separator;

	private final static String TEMP_DIR = FILESEPARATOR + "temp";

	private final static String UPLOAD_FILE_PATH = PropertiesLoader.getUserFilesAbsolutePath() + FILESEPARATOR
			+ "linkslogo";

	private final static String SOURCE_SERVICE = PropertiesLoader.getUserFilesPath() + FILESEPARATOR + "linkslogo";

	@RequestMapping("/list")
	public String list(HttpServletRequest request, ModelMap map,
			@RequestParam(value = "isPass", required = false) String isPass,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "webType", required = false) String webType,
			@RequestParam(value = "type", required = false) String type)
	{
		// 记录本次查询条件
		map.put("isPass", isPass);
		map.put("name", name);
		map.put("webType", webType);
		map.put("type", type);
		try
		{
			// 查询数据列表
			Pagination page = new Pagination(request);
			page.setPageSize(this.getPageSize(request));
			// 排序规则
			LinkedHashMap<String, OrderType> sortMap = new LinkedHashMap<String, OrderType>();
			sortMap.put("sort", OrderType.ASC);
			sortMap.put("id", OrderType.ASC);
			ServiceResult<List<Links>> result = serviceFactory.getLinksService().findLinksList(page.currentPage,
					page.pageSize, sortMap, isPass, name, webType, type);
			List<Links> linksList = result.getReturnValue();
			for (Links links : linksList)
			{
				if (!validateObjectsNullOrEmpty(links.getLogo()))
				{
					// 将logo置换为相应的图片路径
					links.setLogo("image://" + links.getLogo());
				}
				else
				{
					links.setLogo("无图标");
				}
			}
			if (result.getIsSuccess())
			{
				page.setEntityCount(result.getReturnListSize());
				map.put("linkslist", result.getReturnValue());
				map.put("linksListPage", page);
			}
			return "links/linksmanage";
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return returnError(map, ex);
		}
	}

	@RequestMapping("/preview")
	public String preview(@RequestParam(value = "url", required = false) String url)
	{
		return "redirect:" + url;
	}

	@RequestMapping("/audit")
	public String audit(ModelMap map, HttpServletRequest request, @RequestParam("ids") String ids, String isPass)
	{
		if (validateObjectsNullOrEmpty(ids, isPass))
		{
			return returnError(map, "数据未通过验证!");
		}
		try
		{
			String[] _ids = ids.split(",");
			Long[] idArr = new Long[_ids.length];
			for (int i = 0; i < _ids.length; i++)
			{
				idArr[i] = Long.valueOf(_ids[i]);
			}
			List<Links> lList = serviceFactory.getLinksService().findListByField("id", idArr, Links.class)
					.getReturnValue();
			BoolValue _isPass = BoolValue.valueOf(isPass);
			Date now = new Date();
			for (Links links : lList)
			{
				links.setIsPass(_isPass);
				links.setLastUpdateTime(now);
				links.setChecker(getUserName(request.getSession()));
				serviceFactory.getPersistService().update(links);
			}
			return returnSuccess(request, map, new String(), "/links/list");
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return returnError(map, ex);
		}
	}

	@RequestMapping("/new")
	public String preCeate(ModelMap map)
	{
		map.put("links", new Links());
		return "/links/detail";
	}

	@RequestMapping("/save")
	public String create(ModelMap map, HttpServletRequest request, Links links)
	{
		if (validateObjectsNullOrEmpty(links.getUrl(), links.getName(), links.getType(), links.getSort(),
				links.getWebType()))
		{
			return returnError(map, "数据未通过验证!");
		}
		Links _links = null;
		try
		{
			links.setLastUpdateTime(new Date());
			links.setOperator(getUserName(request.getSession()));
			_links = serviceFactory.getPersistService().save(links);
			// 更新logo路径与名称
			if (null != _links.getLogo() && !"".equals(_links.getLogo()))
			{
				String logoSuffix = _links.getLogo().substring(_links.getLogo().lastIndexOf("."));
				String newLogoName = _links.getId().toString() + logoSuffix;
				_links.setLogo(SOURCE_SERVICE + FILESEPARATOR + newLogoName);
				serviceFactory.getPersistService().update(_links);
				// 将临时文件夹中的logo移动到正式文件夹
				this.moveFile(UPLOAD_FILE_PATH + TEMP_DIR + FILESEPARATOR + getUserName(request.getSession())
						+ logoSuffix, UPLOAD_FILE_PATH + FILESEPARATOR + newLogoName);
			}
			return returnSuccess(map, "/links/list");
		}
		catch (Exception e)
		{
			logger.error(e);
			return returnError(map, e.getMessage());
		}
	}

	@RequestMapping("/get")
	public String get(@RequestParam("id") Long id, ModelMap map)
	{
		// 获取对应的友情链接
		Links links = serviceFactory.getPersistService().get(Links.class, id);

		map.put("links", links);
		return "/links/detail";
	}

	@RequestMapping("/update")
	public String update(ModelMap map, HttpServletRequest request, Links links)
	{
		if (validateObjectsNullOrEmpty(links.getUrl(), links.getName(), links.getType(), links.getSort(),
				links.getWebType()))
		{
			return returnError(map, "数据未通过验证!");
		}
		try
		{
			// 更新logo路径与名称
			if (null != links.getLogo() && !"".equals(links.getLogo())
					&& links.getLogo().toLowerCase().indexOf((SOURCE_SERVICE + TEMP_DIR).toLowerCase()) != -1)
			{
				String logoSuffix = links.getLogo().substring(links.getLogo().lastIndexOf("."));
				File file = new File(UPLOAD_FILE_PATH + TEMP_DIR + FILESEPARATOR + getUserName(request.getSession())
						+ logoSuffix);
				if (file.exists() && file.isFile())
				{
					String newLogoName = links.getId().toString() + logoSuffix;
					// 将临时文件夹中的logo移动到正式文件夹
					this.moveFile(file.getPath(), UPLOAD_FILE_PATH + FILESEPARATOR + newLogoName);
					links.setLogo(SOURCE_SERVICE + FILESEPARATOR + newLogoName);
				}
			}
			else
			{
				Links _links = serviceFactory.getPersistService().get(Links.class, links.getId());
				if (_links.getLogo() != null && !"".equals(_links.getLogo()))
				{
					this.deleteFile(UPLOAD_FILE_PATH + FILESEPARATOR
							+ _links.getLogo().substring(_links.getLogo().lastIndexOf(FILESEPARATOR)));
				}
			}
			links.setOperator(getUserName(request.getSession()));
			links.setLastUpdateTime(new Date());
			serviceFactory.getPersistService().update(links);

			return returnSuccess(map, "/links/list");
		}
		catch (Exception e)
		{
			logger.error(e);
			return returnError(map, e.getMessage());
		}
	}

	@RequestMapping("/delete")
	public String delete(@RequestParam("ids") Long[] ids, ModelMap map, HttpServletRequest request)
	{
		if (ids == null || ids.length <= 0)
		{
			return returnError(map, "要删除的类别不能为空");
		}
		try
		{
			for (int i = 0; i < ids.length; i++)
			{
				Links links = serviceFactory.getPersistService().get(Links.class, ids[i]);
				if (null != links.getLogo() && !"".equals(links.getLogo()))
				{
					this.deleteFile(UPLOAD_FILE_PATH + FILESEPARATOR
							+ links.getLogo().substring(links.getLogo().lastIndexOf(FILESEPARATOR) + 1));
				}
				serviceFactory.getPersistService().delete(Links.class, ids[i]);
			}

			return returnSuccess(map, "/links/list");
		}
		catch (Exception e)
		{
			logger.error(e);
			return returnError(map, e.getMessage());
		}
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> upload(@RequestParam("uploadLogo") MultipartFile uploadLogo, ModelMap map,
			HttpServletRequest request)
	{
		Map<String, Object> params = new HashMap<String, Object>();
		// 允许的文件后缀
		String[] allowSuffix = new String[] { "jpg", "gif" };
		// 获取上传文件信息
		String orignalName = uploadLogo.getOriginalFilename();
		String suffix = orignalName.substring(orignalName.lastIndexOf(".") + 1);
		// 判断文件类型
		for (int i = 0; i < allowSuffix.length; i++)
		{
			if (suffix.equalsIgnoreCase(allowSuffix[i]))
			{
				break;
			}
			else if (i == allowSuffix.length - 1)
			{
				params.put("msg", "不支持的图片类型，请确认是否为" + Arrays.toString(allowSuffix) + "格式！");
				// map.put("response", params);
				return params; // "links/message";
			}
		}
		InputStream is = null;
		OutputStream os = null;
		try
		{
			// 保存文件名称
			String saveNameTemp = getUserName(request.getSession()) + "." + suffix;
			File file = new File(UPLOAD_FILE_PATH + TEMP_DIR + FILESEPARATOR + saveNameTemp);
			if (!file.getParentFile().exists())
			{
				file.getParentFile().mkdirs();
			}
			// 开始上传
			is = uploadLogo.getInputStream();
			os = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int bytesum = 0;
			int byteread = 0;
			while ((byteread = is.read(buffer)) != -1)
			{
				bytesum += byteread;
				os.write(buffer, 0, byteread);
				os.flush();
			}
			params.put("imgurl", SOURCE_SERVICE + TEMP_DIR + FILESEPARATOR + saveNameTemp);
			params.put("imgname", saveNameTemp);
			if (createMiniPic(file, 88, 31))
			{
				params.put("msg", "上传成功，图片以被按比例缩放！");
			}
			else
			{
				params.put("msg", "上传成功");
			}
		}
		catch (Exception ex)
		{
			logger.error(ex);
			params.put("msg", "上传失败");
		}
		finally
		{
			try
			{
				// 关闭流
				if (is != null)
				{
					is.close();
				}
				if (os != null)
				{
					os.close();
				}
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}
		return params;// "links/message";
	}

	public void deleteFile(String file)
	{
		File _file = new File(file);
		if (_file.exists() && _file.isFile())
		{
			_file.delete();
		}
	}

	/**
	 * 移动文件至目标目录
	 */
	public void moveFile(String srcDir, String destDir)
	{
		// 开始上传
		File srcFile = new File(srcDir);
		File destFile = new File(destDir);
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try
		{
			if (srcFile.exists() && srcFile.isFile())
			{
				// 新建文件输入流并对它进行缓冲
				inBuff = new BufferedInputStream(new FileInputStream(srcFile));
				// 新建文件输出流并对它进行缓冲
				outBuff = new BufferedOutputStream(new FileOutputStream(destFile));
				// 缓冲数组
				byte[] b = new byte[1024];
				int len;
				while ((len = inBuff.read(b)) != -1)
				{
					outBuff.write(b, 0, len);
				}
				// 刷新此缓冲的输出流
				outBuff.flush();
			}
		}
		catch (Exception ex)
		{
			logger.error(ex);
		}
		finally
		{
			try
			{
				// 关闭流
				if (inBuff != null)
				{
					inBuff.close();
					srcFile.delete();
				}
				if (outBuff != null)
					outBuff.close();
			}
			catch (Exception ex)
			{
				logger.error(ex);
			}
		}
	}

	/**
	 * 创建缩略图
	 * @param file 上传的文件流
	 * @param height 最小的尺寸
	 * @throws IOException
	 */
	public boolean createMiniPic(File file, float width, float height) throws IOException
	{
		boolean flag = false;
		Image src = javax.imageio.ImageIO.read(file); // 构造Image对象
		int old_w = src.getWidth(null); // 得到源图宽
		int old_h = src.getHeight(null);
		int new_w = 0;
		int new_h = 0; // 得到源图长
		float tempdouble;
		if (old_w >= old_h)
		{
			tempdouble = old_w / width;
		}
		else
		{
			tempdouble = old_h / height;
		}
		if (old_w >= width || old_h >= height)
		{ // 如果文件小于缩略图的尺寸则复制即可
			// 按比例进行缩放
			new_w = Math.round(old_w / tempdouble);
			new_h = Math.round(old_h / tempdouble);// 计算新图长宽
			while (new_w > width && new_h > height)
			{
				if (new_w > width)
				{
					tempdouble = new_w / width;
					new_w = Math.round(new_w / tempdouble);
					new_h = Math.round(new_h / tempdouble);
				}
				if (new_h > height)
				{
					tempdouble = new_h / height;
					new_w = Math.round(new_w / tempdouble);
					new_h = Math.round(new_h / tempdouble);
				}
			}
			BufferedImage tag = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(src, 0, 0, new_w, new_h, null); // 绘制缩小后的图
			FileOutputStream newimage = new FileOutputStream(file); // 输出到文件流
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);
			param.setQuality((float) (100 / 100.0), true);// 设置图片质量,100最大,默认70
			encoder.encode(tag, param);
			encoder.encode(tag); // 将JPEG编码
			newimage.close();
			flag = true;
		}
		return flag;
	}
}
